package com.klaus.ohMySpace.service.Impl;

import com.klaus.ohMySpace.dao.BaseDao;
import com.klaus.ohMySpace.dao.UserDao;
import com.klaus.ohMySpace.entity.User;
import com.klaus.ohMySpace.service.UserService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Mklaus on 15/8/7.
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public BaseDao getBaseDao() {
        return userDao;
    }

    @Override
    public User login(User user) {
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);
        List<User> list = userDao.search(
                dc.add(Restrictions.eq("email", user.getEmail()))
                        .add(Restrictions.eq("password", user.getPassword()))
        );

        if (list.size() > 0)
            return list.get(0);

        return null;
    }

    @Override
    public boolean isExist(User user) {
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);
        List<User> list = userDao.search(dc.add(Restrictions.eq("email",user.getEmail())));
        if (list.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    public User register(User user) {
        userDao.save(user);
        return login(user);
    }
}
